package com.quick.send.contact.activity;

import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.quick.send.contact.model.Contact;
import com.quick.send.contact.model.ContactCustomAdapter;
import com.quick.send.contact.util.DataHolder;

public class SelectReceiversActivity extends QuickActivity {

	ListView listViewReceiver;
	List<Contact> receiverItemList;
	ContactCustomAdapter adapterForReceiver;
	/** The view to show the ad. */
	private AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_receiver_activity);
		// Create an ad.
		adView = (AdView) this.findViewById(R.id.adView);
		if (isNetworkConnected()) {
			AdRequest adRequest = new AdRequest.Builder().build();
			adView.loadAd(adRequest);
		} else {
			adView.setVisibility(View.GONE);
		}
		//
		this.handleListViewSelectReceiver();
		this.handleAction();
		// Keep the selected receiver before
		this.showCurrentSelectedReceiverWhenBack();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.quick, menu);
		return true;
	}

	private void handleListViewSelectReceiver() {
		listViewReceiver = (ListView) findViewById(R.id.receiverListView);
		receiverItemList = DataHolder.getInstance().getListContactData();
		adapterForReceiver = new ContactCustomAdapter(this, receiverItemList);
		listViewReceiver.setAdapter(adapterForReceiver);
		// handle filter
		listViewReceiver.setTextFilterEnabled(true);
		EditText filterText = (EditText) findViewById(R.id.filterReceiverText);
		filterText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				adapterForReceiver.getFilter().filter(s);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void handleAction() {
		// Handle button cancel and done
		ImageView imgBack = (ImageView) findViewById(R.id.imgBackToSelectContact);
		imgBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Store selected contacts and go back
				storeSelectedReceivers();
				// Back to previous screen
				startActivity(new Intent(SelectReceiversActivity.this,
						SelectContactsActivity.class));
				// Finish activity
				finish();

			}
		});

		ImageView imgDone = (ImageView) findViewById(R.id.imgDoneReceiver);
		imgDone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Store selected contacts and go to next screen
				storeSelectedReceivers();
				// Go to next screen
				Intent intent = new Intent(SelectReceiversActivity.this,
						SendSMSActivity.class);
				startActivity(intent);
				// Finish this activity
				finish();

			}
		});

	}

	private void storeSelectedReceivers() {

		StringBuffer listContactInfoToStore = new StringBuffer();
		StringBuffer listContactIdToStore = new StringBuffer();
		for (Contact contact : adapterForReceiver.getOriginalContactList()) {
			if (contact.isSelected()) {
				contact.setMobileNumbers(getPhoneNumber(contact.getContactId()));

				for (String phoneNum : contact.getMobileNumbers())
					listContactInfoToStore.append(phoneNum + ";");

				listContactIdToStore.append(contact.getContactId() + ";");
			}
		}
		SharedPreferences preferencesSelectedContacts = getSharedPreferences();
		Editor editor = preferencesSelectedContacts.edit();
		editor.putString(PREFS_RECEIVER_CONTACTS,
				listContactInfoToStore.toString());
		editor.putString(PREFS_RECEIVER_CONTACT_IDS,
				listContactIdToStore.toString());
		editor.commit();

	}

	private void showCurrentSelectedReceiverWhenBack() {
		SharedPreferences sharedPreferences = getSharedPreferences();
		// Get selected contacts
		String selectedReceiverIds = sharedPreferences.getString(
				PREFS_RECEIVER_CONTACT_IDS,
				getResources().getString(R.string.no_contact_found));

		if (!selectedReceiverIds.equals("")
				&& !selectedReceiverIds.equalsIgnoreCase(getResources()
						.getString(R.string.no_contact_found))) { // if have any
																	// selected
																	// receiver

			String[] listIDs = selectedReceiverIds.split(";");

			for (Contact contact : adapterForReceiver.getOriginalContactList()) {
				for (String contactID : listIDs) {
					if (contact.getContactId().equals(contactID)) {
						contact.setSelected(true);
					}
				}
			}

		}

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		clearSharedPreferences();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (adView != null) {
			adView.resume();
		}
	}

	@Override
	public void onPause() {
		if (adView != null) {
			adView.pause();
		}
		super.onPause();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}
}
